package cn.com.dhcc.ddi.task.service.load.impl;

import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.tag.CommonStaticCode;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.app.pub.core.consts.DdiProperties;
import cn.com.dhcc.ddi.datamapping.dao.DataMappingDao;
import cn.com.dhcc.ddi.datamapping.vo.DataMapping;
import cn.com.dhcc.ddi.datasource.dao.DataSourceDao;
import cn.com.dhcc.ddi.datasource.vo.DataSourceConfVo;
import cn.com.dhcc.ddi.datasource.vo.DataSourceVo;
import cn.com.dhcc.ddi.task.dao.TaskExecuteLogDao;
import cn.com.dhcc.ddi.task.service.Result;
import cn.com.dhcc.ddi.task.service.load.LDataSourceInterface;
import cn.com.dhcc.ddi.task.vo.Task;
import cn.com.dhcc.ddi.task.vo.TaskExecuteLog;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @日期：2017/5/10 09:42
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Service(AppIocBean.L_DATASOURCE_LOCALDISK_IMPL)
public class LDataSourceLocalDiskImpl implements LDataSourceInterface {
    private static Logger logger = Log.getLogger(Log.LOGTYPE.DDI);
    @Autowired
    private TaskExecuteLogDao taskExecuteLogDao;
    @Autowired
    private DataMappingDao dmDao;
    @Autowired
    private DataSourceDao dsDao;


    @Override
    public Result loadData(Task task, String taskLogId) throws ServiceException, DaoException {
        //映射根目录
        String transformPath = DdiProperties.APP_UPLOAD_FILEDATA_PATH + File.separator + TaskExecuteLog.LINK_TYPE.TRANSFORM.getEname() + File.separator + task.getId() + File.separator + taskLogId;
        DataMapping dm = dmDao.get(task.getMpId());
        DataSourceVo ds = dsDao.get(dm.getDestDsId());
        DataSourceConfVo dsConfVo = JsonUtil.toObject(ds.getConf(), DataSourceConfVo.class);
        File loadFolder = new File(dsConfVo.getDiskDirectory());
        Result result = new Result();
        result.setTaskLogId(taskLogId);
        logger.info("开始执行load...");
        //记录加载环节日志
        TaskExecuteLog loadLog = new TaskExecuteLog();
        loadLog.setId(UUIDGenerator.getUUID());
        loadLog.setTaskId(task.getId());
        loadLog.setLinkType(TaskExecuteLog.LINK_TYPE.LOAD.getCode());
        loadLog.setLinkStartTime(new Date());
        loadLog.setMtime(new Date());
        loadLog.setGroupId(taskLogId);

        taskExecuteLogDao.insert(loadLog);
        result.setLinkLogId(loadLog.getId());
        //获取抽取日志
        TaskExecuteLog transformtLog = taskExecuteLogDao.getTransformtLog(taskLogId);
        if (transformtLog.getLogStatus() == null || transformtLog.getLogStatus().equalsIgnoreCase(CommonStaticCode.SUCCESSFAIL.FAIL.getStatus()) || transformtLog.getLogStatus().equalsIgnoreCase("")){
            result.setStatus(CommonStaticCode.SUCCESSFAIL.FAIL.getStatus());
            result.setMsg("映射数据失败");
            if(transformtLog.getLogStatus().equalsIgnoreCase("") || transformtLog.getLogStatus() == null){
                transformtLog.setLogStatus(CommonStaticCode.SUCCESSFAIL.FAIL.getStatus());
                transformtLog.setLinkEndTime(new Date());
                taskExecuteLogDao.update(transformtLog);
            }
            return result;
        }
        if(transformtLog.getTotal() == 0 ){
            String msg = "本次任务没有交换数据.";
            result.setStatus(CommonStaticCode.SUCCESSFAIL.SUCCESS.getStatus());
            result.setMsg(msg);
            loadLog.setLogStatus(CommonStaticCode.SUCCESSFAIL.SUCCESS.getStatus());
            loadLog.setLinkEndTime(new Date());
            loadLog.setLinkSummary(msg);
            loadLog.setTotal(0);
            taskExecuteLogDao.update(loadLog);
            return result;
        }
        //先复制新的文件到指定目录中，操作复制后的数据文件，防止读取文件过程中错误，导致文件失效
        List<String> filePathList = JsonUtil.toObjectList(transformtLog.getLinkDataFilePath(), String.class);
        if (StringUtils.isEmpty(filePathList)) {
            logger.error("获取到数据抽取文件路径失败。路径为空。");
            //如果查询出的文件目录为空，则不进行复制，只更新数据库状态，不进行后续操作
            result.setStatus(CommonStaticCode.SUCCESSFAIL.FAIL.getStatus());
            result.setMsg("获取到数据抽取文件路径失败。路径为空。");
            return result;
        }
        logger.info("[load]开始接收文件...");
        //文件名称
        List<String> fileDirList = new ArrayList<String>();
        //文件服务器存储路径
        List<File> fileList = new ArrayList<File>();
        for (String relativePath : filePathList) {
            String loadDataPath = loadFolder + File.separator + relativePath;
            File transformFile = new File(transformPath + File.separator + relativePath);
            File loadFile = new File(loadDataPath);
            try {
                FileUtils.copyFile(transformFile, loadFile);
                fileList.add(loadFile);
                fileDirList.add(loadFile.getAbsolutePath());
                transformFile.delete();
            } catch (IOException e) {
                logger.error("[load]接收文件 " + transformFile + " 发生异常", e);
                result.setStatus(CommonStaticCode.SUCCESSFAIL.FAIL.getStatus());
                result.setMsg("[load]接收文件 " + transformFile + " 发生异常");
                return result;
            }
        }
        String linkSummary = "";

        if(fileList.size() == transformtLog.getTotal()){
            loadLog.setLinkDataFilePath(JsonUtil.toJson(fileDirList));
            linkSummary = createLoadContentDetail(fileList);
            loadLog.setTotal(fileList.size());
            loadLog.setLogStatus(CommonStaticCode.SUCCESSFAIL.SUCCESS.getStatus());
            result.setStatus(CommonStaticCode.SUCCESSFAIL.SUCCESS.getStatus());
            result.setMsg("[load]接收成功 ");

            File transformFolder = new File(transformPath);
            if (transformFolder.exists()){
                transformFolder.delete();
            }
        }else{
            linkSummary = "接收失败";
            loadLog.setLogStatus(CommonStaticCode.SUCCESSFAIL.FAIL.getStatus());
            result.setStatus(CommonStaticCode.SUCCESSFAIL.FAIL.getStatus());
            result.setMsg("[load]接收失败 ");
        }
        loadLog.setLinkSummary(linkSummary);
        loadLog.setLinkEndTime(new Date());
        taskExecuteLogDao.update(loadLog);
        return result;
    }
    /**
     * 生成映射详情
     * @param transMap 映射结果记录
     * @return
     */
    private String  createLoadContentDetail(List<File> fileList)  {
        logger.info("进入方法createCendContentDetail().");
        StringBuilder rs = new StringBuilder();
        //将转换前后的表名对应关系取出
        int sum = 0;
        StringBuilder files = new StringBuilder();
        for (File file:fileList){
            files.append("文件：").append(file.getName()).append("\r\n");
        }
        rs.append("数据接收结果,总数:").append(fileList.size()).append("\r\n").append(files);
        logger.info("执行结束createTransContentDetail().返回值：" + rs.toString());
        return rs.toString();
    }
}
